package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import sun.plugin2.main.server.ResultID;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_LIST;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryOfTypeList() {
        // 从 redis 查
        List<String> shopTypeStringList = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_LIST, 0, -1);
        // 存在，取出
        if (shopTypeStringList.size() != 0) {
            ArrayList<ShopType> shopTypeList = new ArrayList<>();
            for (String s : shopTypeStringList) {
                shopTypeList.add(JSONUtil.toBean(s, ShopType.class));
            }
            return Result.ok(shopTypeList);
        }
        // 不存在，从数据库查 mybatis plus
        List<ShopType> shopTypeListFromDB = query().orderByAsc("sort").list();
        // 数据库不存在
        if (shopTypeListFromDB.isEmpty()) {
            return Result.fail("店铺类型不存在");
        }
        // 数据库存在，存入 redis，并且返回
        for (ShopType shopType : shopTypeListFromDB) {
            // ShopType 转 JSON
            shopTypeStringList.add(JSONUtil.toJsonStr(shopType));
        }
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_TYPE_LIST, shopTypeStringList);
        return Result.ok(shopTypeListFromDB);
    }
}
